﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using ThoiTrang.Entities;
using System.Collections.Generic;
using ThoiTrang.Business;
using System.IO;
using System.Xml;
using System.Text;

/// <summary>
/// Summary description for TTHelper
/// </summary>
public class TTHelper
{
    public TTHelper()
    {
       
    }

    //Dem so tu trong mot chuoi
    public static int WordCounter(string str)
    {
        string[] arr = str.Split(' ');
        return arr.Length;
    }

    //Lay substring cua 1 chuoi bang cach lay so tu bang count
    public static string GetSubString(string str, int count)
    {
        string[] arr = str.Split(' ');
        if (arr.Length < count) return str;        
        string[] subArr= new string[count];
        for(int i=0;i<count;i++)
            subArr[i] = arr[i];
        return string.Join(" ", subArr);
    }

    public static string GetUpperCaseFirstLetter(string str)
    {
        string first = str.Substring(0, 1);
        str = str.Substring(1);
        return str.Insert(0, first.ToUpper());
    }

    public static string GetArticleTitle(string title)
    {
        if (title.Length <= FOConstants.ItemCharCount) return title;

        string res = title.Trim().Substring(0, FOConstants.ItemCharCount);
        int id = res.LastIndexOf(' ');
        if (id != -1)
            res = string.Concat(res.Substring(0, id), "...");
        return res;
    }

    //Get value for Param request 'Vn'
    public static string GetVnValue(string mainName, string subName)
    {
        if(mainName.Equals("thoi trang", StringComparison.OrdinalIgnoreCase))
              return string.Format("thoi-trang-{0}", subName.Trim().Replace(' ', '-'));
        return subName.Trim().Replace(' ', '-');
    }

    //Lay duong dan den image hien thi tren header
    public static string GetHeaderImagePath(string subName)
    {
        return String.Format("hinh-thoi-trang/{0}-hp.gif", subName.Trim().Replace(' ', '-'));
    }

    public static string GetImagePath(a_Article art)
    {
        string path = art.KTitle.Trim().Replace(' ', '-');
        path = string.Concat(path, "-", art.FYear.ToString(), "-l", art.ID.ToString());
        return String.Format("../hinh-anh-nguoi-mau/{0}.jpg", path);
    }

    //Lay cac image path cho 5 images tren page index
    public static string GetFeaturedImagePath(a_Article art)
    {
        string path = art.KTitle.Trim().Replace(' ', '-');
        path = string.Concat(path, "-", art.FYear.ToString(), "-c", art.ID.ToString(), art.FeaturedType.ToString());
        return String.Format("../hinh-anh-nguoi-mau/{0}.jpg", path);
    }

    public static string GetDetailLink(a_CatMain catMain, a_CatSub catSub)
    {
        string link = "~/listing.aspx";
        link += String.Format("?{0}={1}", FOConstants.QSP_VN, GetVnValue(catMain.Name, catSub.Name));
        link += String.Format("&{0}={1}", FOConstants.QSP_MCID, catMain.CatID);
        link += String.Format("&{0}={1}", FOConstants.QSP_SCID, catSub.SubCatID);
        link += String.Format("&{0}={1}", FOConstants.QSP_CKID, "");
        return link;
    }

    public static string GetDetailLinkByGenerate(a_CatMain catMain, a_CatSub catSub)
    {
        string link = "listing.aspx";
        link += String.Format("?{0}={1}", FOConstants.QSP_VN, GetVnValue(catMain.Name, catSub.Name));
        link += String.Format("&{0}={1}", FOConstants.QSP_MCID, catMain.CatID);
        link += String.Format("&{0}={1}", FOConstants.QSP_SCID, catSub.SubCatID);
        link += String.Format("&{0}={1}", FOConstants.QSP_CKID, SessionManager.GetCookie());
        return link;
    }

    //Generate ra cac Left Menu
    public static void GenerateMenuLeftHtmlCode(int groupId, string path)
    {
        try
        {
            string codeStr = "<Code>\n";
            List<a_CatMain> catMains = a_CatMainService.Geta_CatMainListByGroup(groupId);
            foreach (a_CatMain catMain in catMains)
            {
                codeStr += String.Format("\t\t\t\t<h2>{0}</h2>\n", catMain.UName);
                codeStr += "\t\t\t\t<ul class=\"category\">\n";

                List<a_CatSub> catSubs = a_CatSubService.Geta_CatSubListByCatMain(catMain.CatID);
                for (int i = 0; i < catSubs.Count; i++)
                {
                    string link = TTHelper.GetDetailLinkByGenerate(catMain, catSubs[i]);
                    if (i % 2 == 0)
                        codeStr += String.Format("\t\t\t\t\t<li><a href=\"{0}\">{1}</a></li>\n", link, catSubs[i].UName);
                    else
                        codeStr += String.Format("\t\t\t\t\t<li class=\"se\"><a href=\"{0}\">{1}</a></li>\n", link, catSubs[i].UName);
                }

                codeStr += "\t\t\t\t</ul>\n";
            }
            codeStr += "</Code>\n";
                       
            FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);
            sw.WriteLine(codeStr);
            sw.Close();
        }
        catch (Exception ex)
        {
        }
    }

    protected static string GenerateString(string filename)
    {
        StringBuilder result = new StringBuilder();

        //string chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //Random r = new Random();
        //for (int i = 0; i < 8; i++)
        //{
        //    result.Append(chars[r.Next(chars.Length)]);
        //}
        char[] arrChar = { '0','1','2','3','4','5','6','7','8','9',
                            'a','b','c','d','e','f','g','h','i','j','k','l','m',
                            'n','o','p', 'q','r','s','t','u','v','w','x','y','z',
                            'A','B','C','D','E','F','G','H','I','J','K','L','M',
                            'N','O','P', 'Q' ,'R','S','T','U','V','W','X','Y','Z'
                         };
        int leng = 62;
        StreamReader rd = new StreamReader(filename);
        char[] sep = { ',' };
        string nd = rd.ReadToEnd();
        string[] arrStr = nd.Split(sep);
        rd.Close();
        int[] arrInt = new int[8];

        for (int i = 0; i < 8; i++)
        {
            arrInt[i] = int.Parse(arrStr[i]);
            result.Append(arrChar[arrInt[i]]);
        }
        arrInt[7]++;
        for (int i = 7; i >= 0; i--)
        {            
            if (arrInt[i] == leng)
            {
                arrInt[i] = 0;
                arrInt[i - 1]++;
            }
        }
        string str = "";
        for (int i = 0; i < 8; i++)
        {
            str += arrInt[i];
            if (i != 7)
                str += ",";
        }
        StreamWriter wt = new StreamWriter(filename);
        wt.WriteLine(str);
        wt.Close();
        return result.ToString();
    }
    public static string GetRandomCkid(string filename, string ip)
    {
        bool isOK = false;
        string ssid = GenerateString(filename);
        while(!isOK)
        {
            a_Session session = new a_Session();
            session.SessionID = ssid;
            session.Time_stamp = DateTime.Now;
            session.Login_Status = false;
            session.RemoteIP = ip;
            try
            {
                a_SessionService.Createa_Session(session);
                isOK = true;
            }
            catch (Exception ex)
            {
                ssid = GenerateString(filename);
                isOK = false;
            }
        }       
        return ssid;
    }

    public static void UpdateSession(string paramRequest)
    {
        if (String.IsNullOrEmpty(paramRequest)) return;
        try
        {
            a_Sessions_SService.Updatea_Sessions_S(paramRequest);
        }
        catch (Exception ex)
        {
        }
    }
}

